import { Ref, unref } from 'vue'

/**
 * 表单校验
 * @param ref 节点
 * @param isGetError 是否获取错误项
 */
export async function validate(ref: Ref | any, isGetError = false): Promise<boolean | { valid: boolean; object: any }> {
  const validateFn = unref(ref).validate
  return new Promise((resolve) => validateFn((valid: boolean, object: any) => (isGetError ? resolve({ valid, object }) : resolve(valid))))
}

/**
 * 对部分表单字段进行校验的方法
 * @param ref 节点
 * @param props 字段属性
 */
export async function validateField(ref: Ref | any, props: Array<string> | string): Promise<string> {
  const validateFieldFn = unref(ref).validateField
  return new Promise((resolve) => validateFieldFn(props, (errorMessage: string) => resolve(errorMessage)))
}

/**
 * 重置表单
 * @param ref 节点
 */
export function resetFields(ref: Ref | any): void {
  const resetFieldsFn = unref(ref).resetFields
  resetFieldsFn()
}

/**
 * 移除表单项的校验结果
 * @param ref 节点
 * @param props 字段属性
 */
export function clearValidate(ref: Ref | any, props?: Array<string> | string): void {
  const clearValidateFn = unref(ref).clearValidate
  props ? clearValidateFn(props) : clearValidateFn()
}

/**
 * 手机号校验
 * @param str 要校验的字段
 */
export const isPhone = (str: string) => /^[1][3,4,5,7,8,9][0-9]{9}$/.test(str)

/**
 * 座机校验
 * @param str 要校验的字段
 */
export const isTel = (str: string) => /^(0\d{2,3}-){0,1}\d{7,8}$/.test(str)

/**
 * 正实数校验
 * @param str 要校验的字段
 */
export const isPositiveFloat = (str: string) => /^\d+\.*\d*$/.test(str)

/**
 * 获取格式为YYYY-MM-DD的当前日期
 */
export function getCurrentDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}